<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require 'global_default_function.php';

function writeData($database, $data, $user) {
	$datArray = [];
	$serverData = date('Y-m-d');
	foreach ($data as $keys => $value ) {
		if( $keys > 0 ) {
			$wrtData = explode('	', $value);
			if( count($wrtData) == 11 ) {
				$rebate = $user['rebate'];
				$wrtData[0]    = trim($wrtData[0]); //推广计划
				$wrtData[1]    = trim($wrtData[1]); //推广计划ID
				$wrtData[2]    = trim($wrtData[2]); //日期
				$wrtData[3]    = trim($wrtData[3]); //小时
				$wrtData[4]    = trim($wrtData[4]); //账户
				$wrtData[5]    = trim($wrtData[5]); //账户ID
				$wrtData[6]    = trim($wrtData[6]); //消费
				$wrtData[7]    = trim($wrtData[7]); //平均点击价格
				$wrtData[8]    = trim($wrtData[8]); //点击量
				$wrtData[9]    = trim($wrtData[9]); //展现量
				$wrtData[10]   = rtrim($wrtData[10], '%'); //点击率
				$wrtData[11]   = cashPrice($rebate, $wrtData[6]); //现金消费
				$datatime      = strtotime(date("{$wrtData[2]} {$wrtData[3]}:01:01"));
				$md5           = md5($user['companyId'].$wrtData[1].$wrtData[2].$wrtData[3].$wrtData[5]);
				$res = $database->query("select `id`, `rebate` from cfg_hours where md5 = '{$md5}' LIMIT 1");
				if( isset($res[0]['id']) ) {
					if( $serverData != date('Y-m-d', strtotime($wrtData[2])) ) {
						$rebate = $res[0]['rebate'];
						$wrtData[11] = cashPrice($res[0]['rebate'], $wrtData[6]); //现金消费
					}
					$database->query( " UPDATE cfg_hours SET `contact` = '{$user['contact']}', `customerid` = '{$user['customerid']}', `campaign` = '{$wrtData[0]}', `datatime` = '{$datatime}', `impression` = '{$wrtData[9]}', `rebate` = '{$rebate}', `clicks` = '{$wrtData[8]}', `cost` = '{$wrtData[6]}',
   					`cash` = '{$wrtData[11]}', `cpc` = '{$wrtData[7]}', `ctr` = '{$wrtData[10]}' WHERE id = '{$res[0]['id']}'; ");
				} else {
					$database->query("INSERT INTO cfg_hours (`userid`, `userType`, `bazaarId`, `contact`, `customerid`, `username`, `datatime`, `companyId`, `campaignid`, `campaign`, `rebate`, `impression`, `clicks`, `cost`, `cash`, `cpc`, `ctr`, `copynumber`, `copycost`, `md5` )
					  values ( '{$wrtData[5]}', 1, '{$user['bazaarId']}', '{$user['contact']}', '{$user['customerid']}', '{$wrtData[4]}', '{$datatime}', '{$user['companyId']}','{$wrtData[1]}', '{$wrtData[0]}', 
						'{$rebate}', '{$wrtData[9]}', '{$wrtData[8]}', '{$wrtData[6]}', '{$wrtData[11]}', '{$wrtData[7]}', '{$wrtData[10]}', 0, 0, '{$md5}')" );
				}
			}
		}
	}
	updateTime($database, $user, 2);
}

run(function() use ($argv) {

	showMessage('读取百度时段数据.' );

	$config = getConfig();
	$database = new MySQL;
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

  $userList = $database->query('SELECT `id`, `companyId`, `bazaarId`, `userid`, `contact`, `customerid`, `username`, `password`, `token`, `rebate` FROM cfg_expand where status = 1 and userType = 1');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}

	foreach ($userList as $user) {
		go(function() use ($config, $user)  {
			$database = new MySQL;
			$connect = $database->connect($config);
			if( $connect === false) {
				return;
			}
			showMessage($user['username'].'请求时段报告数据.' );
			$reportId = getProfessionalReportId(json_encode ( [ 'header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ],
   			'body'=> ['reportRequestType'=> ['performanceData'=> ['cost', 'cpc', 'click', 'impression', 'ctr' ], 'levelOfDetails'=> 3,
				'startDate'=> date("Y-m-d", strtotime("-1 day")), 'endDate'=> date("Y-m-d", strtotime("-1 day")), 'unitOfTime'=> 7, 'reportType'=> 10, 'statRange' => 3, 'attributes'=> null, 'device' => 2 ]] ]));
			if( $reportId['code'] == 403 ) {
				showMessage($reportId['data']);
				return;
			}
			showMessage($user['username'].'读取时段报告状态.' );
			$reportFilePath = getReportFileUrl($user, $reportId['data']->reportId);
			if(!$reportFilePath) {
				showMessage($user['username'].'请求时段报告超时.' );
				return;
			}
			showMessage($user['username'].'时段报告下载地址: ' . $reportFilePath );
			$reportFiles = getReportFiles($reportFilePath);
			if( $reportFiles === false ) {
				updateTime($database, $user, 2);
				showMessage($user['username'].'时段报告暂无数据.' );
				return;
			}
			writeData($database, $reportFiles, $user);
		});
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');